package com.ledim.share;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import com.ledim.share.ex.BOauth2AccessToken;
import com.sina.weibo.sdk.auth.Oauth2AccessToken;
import java.io.File;

/**
 * 该类用于保存Oauth2AccessToken到sharepreference，并提供读取功能
 *
 * @author xiaowei6@staff.sina.com.cn
 */
public class AccessTokenKeeper {

    private static final String PREFERENCES_NAME = "com_weibo_sdk_android";
    private static final String KEY_UID = "uid";
    private static final String KEY_ACCESS_TOKEN = "token";
    private static final String KEY_EXPIRES_IN = "expiresTime";
    private static final String KEY_REFRESH_TOKEN = "refresh_token";
    /**
     * 保存accesstoken到SharedPreferences
     *
     * @param context Activity 上下文环境
     * @param token Oauth2AccessToken
     */
    private static File file = null;

    public static void keepAccessToken(Context context, BOauth2AccessToken token) {
        try {

            SharedPreferences pref =
                    context.getSharedPreferences(PREFERENCES_NAME, Context.MODE_APPEND);
            Editor editor = pref.edit();
            editor.putString("token", token.getToken());
            editor.putLong("expiresTime", token.getExpiresTime());
            editor.commit();
        } catch (Exception e) {

            e.printStackTrace();
        }
    }

    public static void keepAccessToken(Context context, Oauth2AccessToken token) {
        try {

            SharedPreferences pref =
                    context.getSharedPreferences(PREFERENCES_NAME, Context.MODE_APPEND);
            Editor editor = pref.edit();
            editor.putString(KEY_UID, token.getUid());
            editor.putString(KEY_ACCESS_TOKEN, token.getToken());
            editor.putString(KEY_REFRESH_TOKEN, token.getRefreshToken());
            editor.putLong(KEY_EXPIRES_IN, token.getExpiresTime());
            editor.commit();
        } catch (Exception e) {

            e.printStackTrace();
        }
        /*try {
			
			OutputStream output = null;
			boolean flag= Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
			if(flag) {
				
				String sd= Environment.getExternalStorageDirectory().getAbsolutePath();
				file= new File(sd+ File.separator+ "letv/letv.sina.token");
				output = new FileOutputStream(file);
			}else{
				//没有存储卡的时候防止程序崩溃    by  wangjun 2014-04-21
				return;
			}
			file.createNewFile();
			String _token = token.getToken();
			String _expiresTile = token.getExpiresTime() + "";
			if (!TextUtils.isEmpty(_token) && !_token.equalsIgnoreCase("null")&& !"0".equals(_expiresTile)) {

				output.write(_token.getBytes());
				output.write("\n".getBytes());
				output.write(_expiresTile.getBytes());
			}
			output.close();
		} catch (IOException e) {

			e.printStackTrace();
		}*/
    }

    /**
     * 清空sharepreference
     *
     * @param context
     */
    public static void clear(Context context) {
        SharedPreferences pref =
                context.getSharedPreferences(PREFERENCES_NAME, Context.MODE_APPEND);
        Editor editor = pref.edit();
        editor.clear();
        editor.commit();
    }

    /**
     * 从SharedPreferences读取accessstoken
     *
     * @param context
     * @return Oauth2AccessToken
     */
    public static Oauth2AccessToken readAccessToken(Context context) {
        Oauth2AccessToken token = new Oauth2AccessToken();
        //BOauth2AccessToken token = new Oauth2AccessToken();
        SharedPreferences pref =
                context.getSharedPreferences(PREFERENCES_NAME, Context.MODE_APPEND);
        token.setToken(pref.getString("token", ""));
        token.setExpiresTime(pref.getLong("expiresTime", 0));
        //更新版本后是否绑定
        //		try {
        //
        //			String sd= Environment.getExternalStorageDirectory().getAbsolutePath();
        //			file= new File(sd+ File.separator+ "letv/letv.sina.token");
        //			if(file!= null&& file.exists()) {
        //
        //				BufferedReader reader= new BufferedReader(new FileReader(file));
        //				String _token= reader.readLine().trim();
        //				String time= reader.readLine().trim();
        //				if(!TextUtils.isEmpty(_token)&& !TextUtils.isEmpty(time)) {
        //
        //					token.setToken(_token);
        //					token.setExpiresTime(Long.parseLong(time));
        //				}
        //				reader.close();
        //			}
        //		} catch (FileNotFoundException e) {
        //
        //			e.printStackTrace();
        //		} catch (IOException e) {
        //
        //			e.printStackTrace();
        //		}

        return token;
    }

    /**
     * 新版
     * 从 SharedPreferences 读取 Token 信息。
     *
     * @param context
     *         应用程序上下文环境
     * @return 返回 Token 对象
     */
    public static Oauth2AccessToken read2ndAccessToken(Context context) {
        if (null == context) {
            return null;
        }

        Oauth2AccessToken token = new Oauth2AccessToken();
        SharedPreferences pref =
                context.getSharedPreferences(PREFERENCES_NAME, Context.MODE_APPEND);
        token.setUid(pref.getString(KEY_UID, ""));
        token.setToken(pref.getString(KEY_ACCESS_TOKEN, ""));
        token.setRefreshToken(pref.getString(KEY_REFRESH_TOKEN, ""));
        token.setExpiresTime(pref.getLong(KEY_EXPIRES_IN, 0));

        return token;
    }

    /**
     * 保存 Token 对象到 SharedPreferences。
     *
     * @param context
     *         应用程序上下文环境
     * @param token
     *         Token 对象
     */
    public static void writeAccessToken(Context context, Oauth2AccessToken token) {
        if (null == context || null == token) {
            return;
        }

        SharedPreferences pref =
                context.getSharedPreferences(PREFERENCES_NAME, Context.MODE_APPEND);
        Editor editor = pref.edit();
        editor.putString(KEY_UID, token.getUid());
        editor.putString(KEY_ACCESS_TOKEN, token.getToken());
        editor.putString(KEY_REFRESH_TOKEN, token.getRefreshToken());
        editor.putLong(KEY_EXPIRES_IN, token.getExpiresTime());
        editor.commit();
    }
}
